package org.platform.tool.util;

import java.net.*;
import java.util.Enumeration;

public class OsInfoUtils {

    private static OsInfoUtils instance = null;

    public static synchronized OsInfoUtils getInstance() {
	if (null == instance) {
	    instance = new OsInfoUtils();
	}
	return instance;
    }

    /**
     * 判断是否是windows系统
     * 
     * @return
     */
    public static boolean isWindows() {
	String os = System.getProperty("os.name");
        return os.toLowerCase().startsWith("win");
    }

    /**
     * 判断是否是linux系统
     * 
     * @return
     */
    public static boolean isLinux() {
	String os = System.getProperty("os.name");
        return os.toLowerCase().equals("linux");
    }

    /**
     * 获取本机IP地址
     * 
     * @return
     */
    public static String getLocalIpAddress() {
	if (isWindows()) {
	    return getWindowsLocalIpAddress();
	} else if (isLinux()) {
	    return getLinuxLocalIpAddress();
	}
	return "";
    }

    /**
     * 获取Windows本机IP地址
     * 
     * @return
     */
    private static String getWindowsLocalIpAddress() {
	try {
	    return InetAddress.getLocalHost().getHostAddress();
	} catch (UnknownHostException e) {
	    e.printStackTrace();
	    return "";
	}
    }

    /**
     * 获取Linux本机IP地址
     * 
     * @return
     */
    private static String getLinuxLocalIpAddress() {

	try {
	    Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
	    InetAddress ip = null;
	    while (allNetInterfaces.hasMoreElements()) {
            NetworkInterface networkInterface = allNetInterfaces.nextElement();
		Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
		while (addresses.hasMoreElements()) {
            ip = addresses.nextElement();
		    if (null != ip && ip instanceof Inet4Address) {
			return ip.getHostAddress();
		    }
		}
	    }
	    return "";
	} catch (SocketException e) {
	    e.printStackTrace();
	    return "";
	}
    }

}
